import Vue from 'vue'
import Tips from '@/assets/utils/tips'

export default {
  async init (before, success, url) {
    if (before) {
      before()
    }
    let wx_config = {
      debug: false, // 如果出错，打开调试
      appId: 'wxd944a4e7e4fbb863',
      timestamp: 0,
      nonceStr: '',
      signature: '',
      jsApiList: ['updateTimelineShareData', 'updateAppMessageShareData', 'chooseImage', 'uploadImage', 'getLocalImgData'] // 需要使用的JS接口列表
    }
    // 服务器缓存key，一般按照自己的项目起个特殊的名字，防止重复
    let cacheName = require('../../../package.json').name + '_wx_config'
    const res2 = await Vue.$api.xHttp.post(
      '/wxApi/wx_new/api/WxInitApi/GetSignByPZ',
      {
        cacheName,
        url
      },
      {
        buried: false,
        load: false,
        defFail: false,
        defEx: false
      }
    )
    if (res2 && res2.ret) {
      // 设置config
      wx_config.timestamp = res2.msg.now
      wx_config.nonceStr = res2.msg.nonceStr
      wx_config.signature = res2.msg.signature
      wx.config(wx_config)
      if (success) {
        wx.ready(() => {
          success()
        })
      }
    } else {
      console.log('res:', res2)
    }
  },
  share (params) {
    wx.updateAppMessageShareData(params)
    wx.updateTimelineShareData(params)
  },
  chooseImage (success, count = 1) {
    wx.chooseImage({
      count, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        if (Vue.$device['isIphone']) {
          wx.getLocalImgData({
            localId: res.localIds[0], // 图片的localID
            success: function (res2) {
              success({ ids: res.localIds, base64: res2.localData }) // localData是图片的base64数据，可以用img标签显示
            }
          })
        } else {
          success({ ids: res.localIds, base64: null })
        }
      }
    })
  },
  uploadImage (localId, folder, success, showLoad = true) {
    if (showLoad) {
      Tips.loading('图片上传中')
    }
    wx.uploadImage({
      localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得
      isShowProgressTips: 0, // 默认为1，显示进度提示
      async success (res) {
        try {
          // 上传图片到服务器
          const result = await Vue.$api.xHttp.post('/dxb/imoral_leaper/api/Common/UploadImageWx', {
            mediaid: res.serverId,
            database: 'iwx_wxd944a4e7e4fbb863',
            folder: folder
          }, {
            load: false,
            validator: () => true,
            defFail: false,
            defEx: false
          })
          if (result) {
            if (showLoad) {
              Tips.loaded()
            }
            success(result.file_path)
          }
        } catch (e) {
          console.log('e:', e)
          if (showLoad) {
            Tips.loaded()
          }
          Tips.alert({ message: '传输异常，请稍后再试' })
        }
      }
    })
  }
}
